package com.seeyon.bugfixtools.custom.datasource.web;

import com.seeyon.bugfixtools.custom.datasource.dto.DatasourceDto;
import com.seeyon.bugfixtools.custom.ResDto;
import com.seeyon.bugfixtools.custom.datasource.dto.SystemVersionDto;
import com.seeyon.bugfixtools.custom.datasource.manager.DynamicDataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author cans
 * @date 2024/5/3
 **/

@Controller
@RequestMapping("/datasource")
public class DataSourceController {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceController.class);

    @Resource
    private DynamicDataSourceConfig dynamicDataSourceConfig;

    @PostMapping("/testConnect")
    @ResponseBody
    public ResDto<Object> testConnect(@RequestBody DatasourceDto datasourceDto) {

        try {
            dynamicDataSourceConfig.buildDataSource(datasourceDto);
            SystemVersionDto systemVersionDto = dynamicDataSourceConfig.getSystemVersionInfo();
            return ResDto.success(systemVersionDto);
        } catch (Exception e) {
            logger.error("获取数据库连接失败",e);
            return ResDto.fait(e.getMessage());
        }
    }


    @PostMapping("/connect")
    @ResponseBody
    public ResDto<String> connect(@RequestBody DatasourceDto datasourceDto) {
        try {
           dynamicDataSourceConfig.buildHikariDataSource();
        } catch (Exception e) {
            logger.error("设置数据库连接池失败",e);
            return ResDto.fait(e.getMessage());
        }
        return ResDto.success();
    }

    @GetMapping("/goHome")
    public String goHome(){

        return "/home/homeIndex.html";
    }
}
